/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tamnhat.ws;

import com.tamnhat.entity.SDPContent;
import com.tamnhat.entity.SDPContentDetail;
import com.tamnhat.ws.Constants;
import com.tamnhat.ws.support.ContentUpdateSupport;
import com.tg.smsgw.ws.AppAuthenticator;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import telsoft.admin.util.AppServer;
import telsoft.sql.Database;
import telsoft.util.DateUtil;
import telsoft.util.StringUtil;

/**
 *
 * @author tuanta
 */
@WebService(serviceName = "ContentUpdate")
public class ContentUpdate {

    /**
     * Web service operation
     */
    Connection cn = null;

    @WebMethod(operationName = "updateContent")
    public String updateContent(@WebParam(name = "content") SDPContent content, @WebParam(name = "contentDetail") SDPContentDetail[] contentDetail, @WebParam(name = "partnerCode") String partnerCode, @WebParam(name = "userName") String userName, @WebParam(name = "password") String password) {
        PreparedStatement pstmtContent = null;
        String strSQLContent = "insert into sdp_contents(content_id,product_id,content_name,created_time,effective_time,expiry_time,effective_type,status)"
                + " values(?,?,?,SYSDATE,to_date(?,'dd/mm/yyyy hh24:mi:ss'),to_date(?,'dd/mm/yyyy hh24:mi:ss'),'1','1')";
        PreparedStatement pstmtDetail = null;
        String strSQLDetail = "insert into sdp_content_details(detail_id,content_id,content,content_index,status,product_content_type)"
                + " values(seq_content.nextval,?,?,?,'1',?)";
        try {
            /* initialization and authentication */
            cn = AppServer.getConnection();
            AppAuthenticator aa = new AppAuthenticator();
            aa.setConnection(cn);
            try {
                aa.verifyPassword(userName, StringUtil.encrypt(password, "SHA"));
            } catch (Exception e) {
                e.printStackTrace();
                return Constants.INVALID_LOGIN;
            }
            cn.setAutoCommit(false);
            /* validation */
            if (content == null) {
                return Constants.NO_CONTENT;
            }
            Vector<Vector> vtProduct = Database.executeQuery(cn, "select product_id from sdp_products where sdp_product_code = '" + content.getSdpProductCode() + "'");
            if (vtProduct.isEmpty()) {
                return Constants.PRODUCT_NOT_FOUND;
            }
            if (contentDetail == null || contentDetail.length == 0) {
                return Constants.NO_CONTENT_DETAIL;
            }
            if (!DateUtil.isDate(content.getEffectiveTime(), "dd/MM/yyyy HH:mm:ss")) {
                return Constants.INVALID_DATE_TIME_FORMAT;
            }
            if (!DateUtil.isDate(content.getExpiryTime(), "dd/MM/yyyy HH:mm:ss")) {
                return Constants.INVALID_DATE_TIME_FORMAT;
            }
            String strProductID = vtProduct.elementAt(0).elementAt(0).toString();
            int index = 1;
            long contentID = Long.parseLong(Database.getSequenceValue(cn, "seq_content"));
            pstmtContent = cn.prepareStatement(strSQLContent);
            pstmtContent.setLong(index++, contentID);
            pstmtContent.setString(index++, strProductID);
            pstmtContent.setString(index++, content.getContentName());
            pstmtContent.setString(index++, content.getEffectiveTime());
            pstmtContent.setString(index++, content.getExpiryTime());
            pstmtContent.executeUpdate();
            /* processing CONTENT_DETAILS */
            pstmtDetail = cn.prepareStatement(strSQLDetail);

            for (int i = 0; i < contentDetail.length; i++) {
                SDPContentDetail sDPContentDetail = contentDetail[i];
                if (sDPContentDetail.getProductContentType() == null) {
                    return Constants.INVALID_CONTENT_TYPE;
                }
                if (!sDPContentDetail.getProductContentType().equals("wappush") && !sDPContentDetail.getProductContentType().equals("text")) {
                    return Constants.INVALID_CONTENT_TYPE;
                }
                int index2 = 1;
                pstmtDetail.setLong(index2++, contentID);
                pstmtDetail.setString(index2++, sDPContentDetail.getContent());
                pstmtDetail.setInt(index2++, sDPContentDetail.getContentIndex());
                pstmtDetail.setString(index2++, sDPContentDetail.getProductContentType());
                pstmtDetail.executeUpdate();
            }
            /* finalization */
            cn.commit();
            cn.setAutoCommit(true);
            return Constants.SUCCESS;
        } catch (Exception e) {
            try {
                cn.rollback();
            } catch (SQLException ex) {
                Logger.getLogger(ContentUpdate.class.getName()).log(Level.SEVERE, null, ex);
            }
            e.printStackTrace();
            return Constants.INTERAL_ERROR;
        } finally {
            Database.closeObject(pstmtContent);
            Database.closeObject(pstmtDetail);
            Database.closeObject(cn);
        }
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "sendSMS")
    public String sendSMS(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "partner_code") String partner_code, @WebParam(name = "product_code") String product_code, @WebParam(name = "from_number") String from_number, @WebParam(name = "to_number") String to_number, @WebParam(name = "content") String content, @WebParam(name = "time_send_sms") String time_send_sms, @WebParam(name = "sms_type") String sms_type, @WebParam(name = "url") String url) {
        //TODO write your implementation code here:        
        CallableStatement cstmt = null;
        try {
            cn = AppServer.getConnection();
            AppAuthenticator aa = new AppAuthenticator();
            aa.setConnection(cn);
            //check username and password
            try {
                aa.verifyPassword(username, StringUtil.encrypt(password, "SHA"));
            } catch (Exception e1) {
                e1.printStackTrace();
                return Constants.ACCOUNT_NOT_CORRECT;
            }                        
            //check partner_code and username
            String rs1 = ContentUpdateSupport.checkPartnerAndAccount(cn, partner_code, username);
            if(!rs1.equals(Constants.SUCCESS)){
                return rs1;
            }
            //check product and partner
            String rs2 = ContentUpdateSupport.checkProductAndPartner(cn, product_code, partner_code);
            if(!rs2.equals(Constants.SUCCESS)){
                return rs2;
            }
            //check sms_type
            String rs3 = ContentUpdateSupport.checkSMSType(sms_type);
            if(!rs3.equals(Constants.SUCCESS)){
                return rs3;
            }
            //check datetime format
            String rs4 = ContentUpdateSupport.checkTime(time_send_sms);
            if(!rs4.equals(Constants.SUCCESS)){
                return rs4;
            }
            //get Product Id
            String product_id = ContentUpdateSupport.getProductIdByCode(cn, product_code);
            if(product_id.equals(Constants.INTERAL_ERROR)){
                return product_id;
            }
            else if(product_id.equals("")){
                return Constants.INVALID_PRODUCT_CODE;
            }
            
           //get Sdp_service_id
            String sdp_service_id = ContentUpdateSupport.getSDPServiceIdByProductId(cn, product_id);
            if(sdp_service_id.equals(Constants.INTERAL_ERROR)){
                return sdp_service_id;
            }
            else if(sdp_service_id.equals("")){
                return Constants.INVALID_SDP_SERVICE_ID;
            }
            
          
            cstmt = cn.prepareCall("{? = call pck_content_management_test.send_sms(?,?,?,?,?,?,?,?) }");
            cstmt.registerOutParameter(1, Types.VARCHAR);
            
            cstmt.setInt(2,Integer.parseInt(product_id));
            cstmt.setString(3, from_number);
            cstmt.setString(4, content);
            cstmt.setString(5, sms_type);
            cstmt.setString(6, to_number);
            cstmt.setString(7, product_code);
            cstmt.setString(8, sdp_service_id);
            cstmt.setString(9, url);
            
            cstmt.executeUpdate();
            
            String rs5 = cstmt.getString(1);
            
            if(rs5.equals("00")){
                return Constants.SUCCESS;
            }
            if(rs5.equals("01")){
                return Constants.CONTENT_NOT_FOUND;
            }            
            if(rs5.equals("99")){
                return Constants.INTERAL_ERROR;
            }            
        } catch (Exception e) {
            e.printStackTrace();
            return Constants.INTERAL_ERROR;
        } finally {
            Database.closeObject(cstmt);
            Database.closeObject(cn);
        }
        return "";
    }
}
